package com.minigame.rpc.network;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcMsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.readableBytes();
        if(length < RpcMsg.HEAD_LENGTH){
            return;
        }
        byteBuf.markReaderIndex();
        int cmd = byteBuf.readInt();
        int headLength = byteBuf.readInt();
        int bodyLength = byteBuf.readInt();
        if(headLength + bodyLength > length-RpcMsg.HEAD_LENGTH){
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] headDatas = new byte[headLength];
        byteBuf.readBytes(headDatas);
        byte[] bodyDatas = new byte[bodyLength];
        byteBuf.readBytes(bodyDatas);
        list.add(new RpcMsg(cmd,headDatas,bodyDatas));
    }
}
